<?php

namespace Shared\Doctrine\DBAL\DataType;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\Type;

/**
 * 
 * @author Peter Yordanov <p.jordanov@object.bg>
 * @copyright (c) 2014, ASPECT.BG Ltd.
 */
class IpType extends Type {

	const NAME = 'ip';

	public function getName() {
		return self::NAME;
	}

	/**
	 * @param array $fieldDeclaration
	 * @param AbstractPlatform $platform
	 * @return string
	 */
	public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform) {
		return $platform->getIntegerTypeDeclarationSQL($fieldDeclaration);
	}

	/**
	 * 
	 * @param string $value
	 * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform
	 * @return integer
	 */
	public function convertToDatabaseValue($value, AbstractPlatform $platform) {
		return ($value !== null) ? self::convertToDbValue($value) : null;
	}
	
	public static function convertToDbValue($value) {
		return sprintf('%u', ip2long($value));
	}

	/**
	 * 
	 * @param integer $value
	 * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform
	 * @return string
	 */
	public function convertToPHPValue($value, AbstractPlatform $platform) {
		if ($value === null) {
			return null;
		}

		return long2ip(sprintf('%d', $value));
	}

}
